import { useEffect, useState } from 'react';
import LocalStorage from './LocalStorage';
import IndexDbStorage from './IndexDbStorage'
import {monitor,clearMonitor} from './Events'
import { IProxy } from './IProxyStorage';
const localStorage = new LocalStorage()
const parseJson = (str)=>{
  if(!str){
    return null
  }
  try{
    return JSON.parse(str)
  }catch (e) {
    return str
  }
}
const useStorage = (key,storage = localStorage)=>{

    const [data,setData] = useState(null)
    const setStorage = (value)=>{
      storage.setItem(key,typeof value === 'string' ? value :JSON.stringify(value))
    }
    const removeStorage = ()=>{
      storage.removeItem(key)
    }
    useEffect(()=>{
      storage.getItem(key,(value)=>{
        setData(parseJson(value))
      })
      monitor(key,(data)=>{
         if(data.key === key){
           setData(data.value)
         }
      })
      return ()=>{
        clearMonitor(key)
      }
    },[])
    return [data,setStorage,removeStorage]
}
const setStorage = (key,value,storage = localStorage)=>{
  storage.setItem(key,typeof value === 'string' ? value :JSON.stringify(value))
}
const removeStorage = (key,storage = localStorage)=>{
  storage.removeItem(key)
}
export default useStorage
export {setStorage,removeStorage,LocalStorage,IndexDbStorage}
